package com.wingscode.modules.sys.controller;

import com.wingscode.common.annotation.SysLog;
import com.wingscode.common.utils.PageUtils;
import com.wingscode.common.utils.R;
import com.wingscode.common.validator.ValidatorUtils;
import com.wingscode.common.validator.group.AddGroup;
import com.wingscode.common.validator.group.UpdateGroup;
import com.wingscode.modules.common.entity.AdvertisementEntity;
import com.wingscode.modules.common.entity.UserEntity;
import com.wingscode.modules.common.service.AdvertisementService;
import com.wingscode.modules.common.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/**
 * 广告
 *
 * @author yan
 */
@RestController
@RequestMapping("/ad")
public class AdvertisementController extends AbstractController {
	@Autowired
	private AdvertisementService advertisementService;
	@Autowired
	private UserService userService;

	
	/**
	 * 广告列表
	 */
	@PostMapping("/list")
	public R list(@RequestBody Map<String, Object> params){
		if (!params.containsKey("type") || params.get("type") == null)
			return R.error("type为空");

		PageUtils page = advertisementService.queryPage(params);

		return R.ok().put("page", page);
	}
	
	/**
	 * 广告详情
	 */
	@RequestMapping("/info/{id}")
	public R info(@PathVariable("id") Long id){
		AdvertisementEntity entity = advertisementService.getById(id);
		if (entity != null) {
			UserEntity user = userService.getById(entity.getUserId());
			if (user != null)
				entity.setUserName(user.getUsername());
		}

        return R.ok().put("info", entity);
	}
	
	/**
	 * 保存
	 */
	@PostMapping("/save")
	public R save(@RequestBody AdvertisementEntity entity){
		entity.setCreateTime(new Date());
		entity.setUpdateTime(new Date());
		entity.setSort(0);
		entity.setStatus(entity.getStatus());
		ValidatorUtils.validateEntity(entity, AddGroup.class);

		advertisementService.save(entity);

		return R.ok();
	}

	/**
	 * 修改广告
	 */
	@PostMapping("/update")
	public R update(@RequestBody AdvertisementEntity entity){
		entity.setUpdateTime(new Date());
		ValidatorUtils.validateEntity(entity, UpdateGroup.class);

		advertisementService.updateById(entity);

		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping("/delete")
	public R delete(@RequestBody Long[] Ids){
		advertisementService.delete(Ids);

		return R.ok();
	}
}
